﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using STEM123.StemService;

namespace STEM123
{
    /// <summary>
    /// Provides content creation facility using image and text.
    /// </summary>
    public partial class CreateContentText : PhoneApplicationPage
    {
        #region Private members

        /// <summary>
        /// String for answer guidance.
        /// </summary>
        private const string AnswerGuidanceText = "Type your answer here...";

        /// <summary>
        /// Index of current slide.
        /// </summary>
        private uint slideIndex;

        /// <summary>
        /// Explain view model instance.
        /// </summary>
        private ExplainViewModel viewModel;

        /// <summary>
        /// Uri of temporary image.
        /// </summary>
        private Uri tempImageUri;

        /// <summary>
        /// Saves content and navigates back to slide creation.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void SaveContent(object sender, EventArgs e)
        {
            LocalSlide localSlide = viewModel.Slides[slideIndex] as LocalSlide;

            // set default values for text slide
            viewModel.Slides[slideIndex].Answer = string.Equals(txtboxAnswer.Text, AnswerGuidanceText) ? string.Empty : txtboxAnswer.Text;
            viewModel.Slides[slideIndex].MediaType = (localSlide.LocalImageSource != null) ? MediaTypes.TextWithImage : MediaTypes.TextOnly;
            viewModel.Slides[slideIndex].MediaDuration = uint.MinValue;
            ((LocalSlide)viewModel.Slides[slideIndex]).LocalMediaSource = null;

            // set image source if only it has changed
            if (tempImageUri != null)
            {
                localSlide.LocalImageSource = viewModel.SetImage(slideIndex, true);
                viewModel.Slides[slideIndex].MediaType = MediaTypes.TextWithImage;
            }

            // navigate
            NavigationService.Navigate(new Uri("/CreateSlides.xaml", UriKind.Relative));
        }

        /// <summary>
        /// Cancels saving of content and navigates back to slide creation / editing.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void CancelContent(object sender, EventArgs e)
        {
            // cancel saving state
            viewModel.SetImage(slideIndex, false);

            // navigate
            NavigationService.Navigate(new Uri("/CreateSlides.xaml", UriKind.Relative));
        }

        /// <summary>
        /// Occurs when user taps on image.
        /// </summary>
        /// <param name="sender">Image reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void imageAnswer_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            PhotoChooserTask getPhoto = new PhotoChooserTask();

            getPhoto.ShowCamera = true;

            // completed event is not fired on UI thread, hence call asynchronously
            getPhoto.Completed += (photoTask, photoEvent) =>
                Dispatcher.BeginInvoke(() =>
                {
                    BitmapImage bitmapAnswer = new BitmapImage();

                    if (photoEvent.ChosenPhoto != null)
                    {
                        // display image
                        bitmapAnswer.SetSource(photoEvent.ChosenPhoto);
                        imageAnswer.Source = bitmapAnswer;
                        txtblockImageGuidance.Visibility = Visibility.Collapsed;

                        // save temporarily
                        tempImageUri = viewModel.WriteImage(slideIndex, photoEvent.ChosenPhoto, true);
                    }
                });

            getPhoto.Show();
        }

        /// <summary>
        /// Occurs when textbox gets focus.
        /// </summary>
        /// <param name="sender">Textbox reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void txtboxAnswer_GotFocus(object sender, RoutedEventArgs e)
        {
            if (string.Equals(txtboxAnswer.Text, AnswerGuidanceText))
            {
                txtboxAnswer.Text = string.Empty;
            }
        }

        /// <summary>
        /// Occurs when textbox loses focus.
        /// </summary>
        /// <param name="sender">Textbox reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void txtboxAnswer_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtboxAnswer.Text.Trim()))
            {
                txtboxAnswer.Text = AnswerGuidanceText;
            }
        }

        #endregion

        #region Protected members

        /// <summary>
        /// Occurs when page is navigated to, from some other page.
        /// </summary>
        /// <param name="e">Navigation event arguments.</param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // determine index of slide
            IDictionary<string, string> parameters = NavigationContext.QueryString;
            slideIndex = uint.Parse(parameters["index"]);

            // load state and initialize controls
            txtblockTerm.Text = viewModel.Term;
            txtblockQuestion.Text = viewModel.Slides[slideIndex].Question;
            txtblockSlide.Text = "Slide " + (slideIndex + 1);

            if (string.IsNullOrEmpty(viewModel.Slides[slideIndex].Answer))
            {
                txtboxAnswer.Text = AnswerGuidanceText;
            }
            else
            {
                txtboxAnswer.Text = viewModel.Slides[slideIndex].Answer;
            }

            if (((LocalSlide)viewModel.Slides[slideIndex]).LocalImageSource != null)
            {
                imageAnswer.Source = viewModel.ReadImage(((LocalSlide)viewModel.Slides[slideIndex]).LocalImageSource);
                txtblockImageGuidance.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        #endregion

        #region Public members

        /// <summary>
        /// Initializes new instance of CreateContentText.
        /// </summary>
        public CreateContentText()
        {
            InitializeComponent();

            // initialize member variables
            viewModel = ExplainViewModel.Instance;
            tempImageUri = null;
        }

        #endregion
    }
}